package com.gogowan.agroenterprise.storage;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.barcode.Intents;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.model.BoxCode;
import com.gogowan.agroenterprise.model.DealerListResult;
import com.gogowan.agroenterprise.model.DealerModel;
import com.gogowan.agroenterprise.model.DealerRequest;
import com.gogowan.agroenterprise.model.OutStorageBoxRequest;
import com.gogowan.agroenterprise.model.OutStorageBoxResult;
import com.gogowan.agroenterprise.model.OutStorageReault;
import com.gogowan.agroenterprise.model.OutStorageRequest;
import com.gogowan.agroenterprise.newview.New_HM_Activity;
import com.gogowan.agroenterprise.utils.Utils;
import com.gogowan.agroenterprise.widget.adapter.DealerSpinnerAdapter;
import com.gogowan.agroenterprise.widget.adapter.XMListViewAdapter;

import org.json.JSONObject;

/**
 * 出库
 * 
 * @author tjh 2017-01-13
 *
 */
public class OutStorageActivity extends Activity implements OnClickListener {
	private ProgressDialog progressDialog;
	
	private TextView dhEdit;
	private Spinner jxsSpinner;
	private DealerSpinnerAdapter jxsSpinnerAdapter;
	private List<DealerModel> dealerList = new ArrayList<DealerModel>();
	private long jxsID;

	private ListView xmListView;
	private XMListViewAdapter xMListViewAdapter;
	private List<BoxCode> boxCodeList = new ArrayList<BoxCode>();

	private Handler myHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				jxsSpinnerAdapter.notifyDataSetChanged();
				break;
			case 1:
				break;
			case 2:
				xMListViewAdapter.notifyDataSetChanged();
				break;
			default:
				break;
			}
		}
	};
	private OutStorageRequest outStorageRequest;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_out_storage);

		initView();
		initValue();

	}

	/**
	 * 初始化界面
	 */
	private void initView() {
		// 经销商
		jxsSpinner = (Spinner) findViewById(R.id.out_storage_jxs_spinner);
		jxsSpinnerAdapter = new DealerSpinnerAdapter(this, dealerList);
		jxsSpinner
				.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> parent,
							View view, int position, long id) {
						// TODO Auto-generated method stub
						jxsID = dealerList.get(position).getId();
					}

					@Override
					public void onNothingSelected(AdapterView<?> parent) {
						// TODO Auto-generated method stub

					}
				});
		jxsSpinner.setAdapter(jxsSpinnerAdapter);

		xmListView = (ListView) findViewById(R.id.out_storage_xmlist);
		xMListViewAdapter = new XMListViewAdapter(this, boxCodeList);
		xmListView.setAdapter(xMListViewAdapter);

		ImageButton fhBtn = (ImageButton) findViewById(R.id.out_storage_fh_btn);
		fhBtn.setOnClickListener(this);
		dhEdit = (TextView) findViewById(R.id.out_storage_dh_edit);
		ImageView smhqdhBtn = (ImageView) findViewById(R.id.out_storage_smhqdh_btn);
		smhqdhBtn.setOnClickListener(this);
		Button smrkxmBtn = (Button) findViewById(R.id.out_storage_smrkxm_btn);
		smrkxmBtn.setOnClickListener(this);
		Button qrrkBtn = (Button) findViewById(R.id.out_storage_qrck_btn);
		qrrkBtn.setOnClickListener(this);
	}

	/**
	 * 初始化数据
	 */
	private void initValue() {

		progressDialog = ProgressDialog.show(this,
				getString(R.string.alert_title),
				getString(R.string.alert_message), true, false);

		DealerRequest dealerRequest = new DealerRequest();
//		dealerRequest.setEnterpriseID(loginResultInfo.getEnterpriseinfo()
//				.getEnterpriseid());
//		dealerRequest.setDealerID(loginResultInfo.getEnterpriseinfo()
//				.getDealerId());
//		dealerRequest.setUserType(loginResultInfo.getEnterpriseinfo()
//				.getUserType());
//		dealerRequest.setUserID(MyApplication.mSettings.getLong("personid",0));

		GetDealerListAsyn getDealerListAsyn = new GetDealerListAsyn();
		getDealerListAsyn.execute(dealerRequest);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent;
		switch (v.getId()) {
		case R.id.out_storage_fh_btn:
			// 返回
			this.finish();
			break;
		case R.id.out_storage_smhqdh_btn:
			// 扫码获取单号
			intent = new Intent(Intents.Scan.ACTION);
			this.startActivityForResult(intent, 10);
			break;
		case R.id.out_storage_smrkxm_btn:
			// 扫描入库箱码
			intent = new Intent(Intents.Scan.ACTION);
			intent.putExtra(Intents.Scan.IS_BULT_MODE, true);
			this.startActivityForResult(intent, 20);
			break;
		case R.id.out_storage_qrck_btn:
			// 确认入库
			if (TextUtils.isEmpty(dhEdit.getText())) {
				Toast.makeText(this, "请输入单号", Toast.LENGTH_LONG).show();
			} else if (boxCodeList.size() <= 0) {
				Toast.makeText(this, "请扫描出售箱码", Toast.LENGTH_LONG).show();
			} else {
				progressDialog = ProgressDialog.show(this,
						getString(R.string.alert_title),
						getString(R.string.alert_message), true, false);

				outStorageRequest = new OutStorageRequest();
//				outStorageRequest.setEnterpriseId(loginResultInfo
//						.getEnterpriseinfo().getEnterpriseid());
//				outStorageRequest.setUserId(loginResultInfo.getUserinfo()
//						.getPersonid());
				outStorageRequest.setPersonid(dhEdit.getText() + "");
				outStorageRequest.setSupplierId(jxsID+"");
				StringBuffer sb=new StringBuffer();
				for (int i = 0; i < boxCodeList.size(); i++) {
					sb.append(boxCodeList.get(i));
					if(i!=boxCodeList.size()-1){
						sb.append(",");
					}
				}
				outStorageRequest.setCodes(sb.toString());
				OutStorageYanAsyn outStorageAsyn = new OutStorageYanAsyn();
				outStorageAsyn.execute(outStorageRequest);
//
//				OutStorageAsyn outStorageAsyn = new OutStorageAsyn();
//				outStorageAsyn.execute(outStorageRequest);
			}
			break;
		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			String codeStr;
			switch (requestCode) {
			case 10:
				// 扫码获取单号
				codeStr = data.getStringExtra(Intents.Scan.RESULT);
				dhEdit.setText(codeStr);
				break;
			case 20:
				// 扫描入库箱码
				ArrayList<String> resultStringList = data
						.getStringArrayListExtra(Intents.Scan.RESULTLIST);
				if (resultStringList == null || resultStringList.size() == 0) {
					return;
				}

				progressDialog = ProgressDialog.show(this,
						getString(R.string.alert_title),
						getString(R.string.alert_message), true, false);

				OutStorageBoxRequest outStorageBoxRequest = new OutStorageBoxRequest();
//				outStorageBoxRequest.setEnterpriseId(loginResultInfo
//						.getEnterpriseinfo().getEnterpriseid());
				outStorageBoxRequest.setBoxCode(resultStringList);

				OutStorageListAsyn outStorageListAsyn = new OutStorageListAsyn();
				outStorageListAsyn.execute(outStorageBoxRequest);
				break;
			default:
				break;
			}
		}
	}

	/**
	 * 获取经销商列表
	 * 
	 * @author tjh
	 *
	 */
	private class GetDealerListAsyn extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(OutStorageActivity.this,
						getString(R.string.server_error), Toast.LENGTH_LONG)
						.show();
			} else {
				com.gogowan.agroenterprise.model.Message message = (com.gogowan.agroenterprise.model.Message) Utils
						.fromJSON((String) res,
								com.gogowan.agroenterprise.model.Message.class);
				String string = Utils.getMessageContent(message);

				if (string == null || string.equals("")) {
					Toast.makeText(OutStorageActivity.this,
							getString(R.string.analyse_error),
							Toast.LENGTH_LONG).show();
				} else {
					DealerListResult dealerListResult = (DealerListResult) Utils
							.fromJSON(string, DealerListResult.class);
					if (dealerListResult.getResult() > 0) {
						if (dealerListResult.getDealer() != null) {
							dealerList.clear();
							dealerList.addAll(dealerListResult.getDealer());
							myHandler.sendEmptyMessage(0);
						}
					} else {
						Toast.makeText(OutStorageActivity.this,
								dealerListResult.getResultinfo(),
								Toast.LENGTH_LONG).show();
					}
				}
			}
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			DealerRequest dealerRequest = (DealerRequest) params[0];
			String json = Utils.toJSON(dealerRequest);
			com.gogowan.agroenterprise.model.Message message = new com.gogowan.agroenterprise.model.Message(
					14000, true, json);
			// String ss = Utils.toJSON(message);
			// Log.i("gggggggggggggggggg===", ss);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}
	}

	/**
	 * 箱码列表
	 * 
	 * @author tjh
	 *
	 */
	private class OutStorageListAsyn extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(OutStorageActivity.this,
						getString(R.string.server_error), Toast.LENGTH_LONG)
						.show();
			} else {
				com.gogowan.agroenterprise.model.Message message = (com.gogowan.agroenterprise.model.Message) Utils
						.fromJSON((String) res,
								com.gogowan.agroenterprise.model.Message.class);
				String string = Utils.getMessageContent(message);

				if (string == null || string.equals("")) {
					Toast.makeText(OutStorageActivity.this,
							getString(R.string.analyse_error),
							Toast.LENGTH_LONG).show();
				} else {
					OutStorageBoxResult outStorageBoxResult = (OutStorageBoxResult) Utils
							.fromJSON(string, OutStorageBoxResult.class);
					if (outStorageBoxResult.getResult() == 15000) {
						if (outStorageBoxResult.getBoxInfo() != null) {
							boxCodeList
									.addAll(outStorageBoxResult.getBoxInfo());
							myHandler.sendEmptyMessage(2);
						}
					} else {
						Toast.makeText(OutStorageActivity.this,
								outStorageBoxResult.getResultinfo(),
								Toast.LENGTH_LONG).show();
					}
				}
			}
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			OutStorageBoxRequest outStorageBoxRequest = (OutStorageBoxRequest) params[0];
			String json = Utils.toJSON(outStorageBoxRequest);
			com.gogowan.agroenterprise.model.Message message = new com.gogowan.agroenterprise.model.Message(
					19000, true, json);
			// String ss = Utils.toJSON(message);
			// Log.i("gggggggggggggggggg===", ss);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.addDepotHeadAndDetailAPP), message);
			return res;
		}
	}


	/**
	 * 确认出库请求
	 * 
	 * @author tjh
	 *
	 */
	private class OutStorageAsyn extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(OutStorageActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
			} else {
				try {
					JSONObject jo=new JSONObject(res.toString());
					Toast.makeText(getApplicationContext(),jo.getString("msg"),
							Toast.LENGTH_LONG).show();
					if(jo.getInt("code")!=200){
						return;
					}
					finish();
				}catch (Exception e){
					e.printStackTrace();
				}
			}
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			OutStorageRequest outStorageRequest = (OutStorageRequest) params[0];
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.addDepotHeadAndDetailAPP), outStorageRequest);
			return res;
		}
	}

	/**
	 * 确认校验请求
	 *
	 * @author tjh
	 *
	 */
	private class OutStorageYanAsyn extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(OutStorageActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
			} else {
				try {
					JSONObject jo=new JSONObject(res.toString());

					if(jo.getInt("code")!=200){
						Toast.makeText(getApplicationContext(),jo.getString("msg"),
								Toast.LENGTH_LONG).show();
						return;
					}
					OutStorageAsyn outStorageAsyn=new OutStorageAsyn();
					outStorageAsyn.execute(outStorageRequest);
				}catch (Exception e){
					e.printStackTrace();
				}
			}
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			OutStorageRequest outStorageRequest = (OutStorageRequest) params[0];
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.addDepotHeadAndDetailCheck), outStorageRequest);
			return res;
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		dealerList.clear();
		xMListViewAdapter = null;
		boxCodeList.clear();
		boxCodeList = null;
	}
}